<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Index_Category extends Controller_Index_Base
{
	public function action_index()
	{ 
        $id       = $this->request->param('id') ? $this->request->param('id') : null;
        $brand_id = $this->request->param('brand_id') ? $this->request->param('brand_id') : null;
        $page     = $this->request->param('page') ? $this->request->param('page') : 1;
         
        $from_price = (isset($_GET['from_price']) && $_GET['from_price']) ? $_GET['from_price'] : null;
        $to_price   = (isset($_GET['to_price']) && $_GET['to_price']) ? $_GET['to_price'] : null;    
        $shop       = (isset($_GET['shop']) && $_GET['shop']) ? $_GET['shop'] : null;
        
        $category = ORM::factory('category', $id);  
        $brand    = null;
        if ($brand_id) {
            $brand = ORM::factory('brand', $brand_id);   
        }     
        $brands   = ORM::factory('brand')->get_brands($category);
        $prices   = ORM::factory('product')->get_available_prices();
        $shops    = ORM::factory('shop')->get_shops($category);
        $products = ORM::factory('product')->get_products($category, $brand, $shop, array('from' => $from_price, 'to' => $to_price), $page);
           
        $content = new View('index/category/index_tpl'); 
        $content->category = $category;
        $content->brand    = $brand;
        $content->childs   = $category->get_childs(); 
        $content->breadcrumbs = $category->get_breadcrumbs();
        $content->brands   = $brands;
        $content->shops    = $shops;
        $content->prices   = $prices;
        $content->products = $products;
        $content->coupons  = ORM::factory('coupon')->get_coupons_by_products($products);
        
        $count = ORM::factory('product')->get_products($category, $brand, $shop, array('from' => $from_price, 'to' => $to_price), $page, true);    
        $content->pagination = array(                                                   
            'page' => $page,
            'per_page' => Model_Product::get_products_per_page(),
            'count' => $count,
        );
        $content->filters = array(
            'from_price' => $from_price,
            'to_price'   => $to_price,
            'shop'       => $shop,
        );
        $content->text = Helper_Index::get_category_index_text($category, $brand);    
        $title = 'Купить '.mb_strtolower($category->name);
        if ($brand) {
            $title .= ' '.$brand->name;        
        }
        $title .= ' в Москве в интернет-магазине недорого, скидки';
        if ($page > 1) {
            $title .= ' - Страница '.$page;    
        }  
        $description = Helper_Index::get_category_index_description($category, $brand);         
        $this->print_template($title, $content, $description);
	}
} 
